package fr.hoteia.appengine.archetype.server.web.servlet;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.images.Image;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;
import com.google.appengine.api.images.Transform;

public class DisplayImageServlet extends HttpServlet {
	 
	private static final long serialVersionUID = 1L;
	private ImagesService imagesService = ImagesServiceFactory.getImagesService(); 
	private static ApplicationContext ctx = null;

	public void init(ServletConfig sc) throws ServletException {
		synchronized (DisplayImageServlet.class) {
			super.init(sc);

			ServletContext context = getServletContext();
			ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		String attributes = request.getPathInfo();
		String[] attributesArray = attributes.split("/");
		String imageSize = attributesArray[1];
		String urlBlobKey = attributesArray[2];
		
		if(!urlBlobKey.equalsIgnoreCase("null")){
			String[] sizes =  imageSize.split("X");
			int width = new Integer(sizes[0]).intValue();
			int height = new Integer(sizes[1]).intValue();

			BlobKey blobKey = new BlobKey(urlBlobKey);
			
			Image masterImage = ImagesServiceFactory.makeImageFromBlob(blobKey); 
	        Transform resize = ImagesServiceFactory.makeResize(width, height); 

	        Image currentImage = imagesService.applyTransform(resize, masterImage);
	        byte[] currentImageBytes = currentImage.getImageData();
	        
	        ServletOutputStream out = response.getOutputStream();
	        response.setContentType(getServletConfig().getServletContext().getMimeType("." + currentImage.getFormat().name()));  
	        out.write(currentImageBytes);
		}
	}
 
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
 
		doGet(request, response);
	}
	
	protected void sendBytes(byte[] bytes, HttpServletResponse response) throws IOException {
		ServletOutputStream servletoutputstream = response.getOutputStream();
		servletoutputstream.write(bytes);
		servletoutputstream.flush();
	}
}